package com.example.modulemine.view.activity.mine;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.util.Log;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.example.baselibs.base.activity.BaseToolBarActivity;
import com.example.baselibs.entity.Result;
import com.example.baselibs.entity.bean.UpdatedInfo;
import com.example.baselibs.net.RetrofitManager;
import com.example.baselibs.net.service.UserApi;
import com.example.baselibs.router.path.ModuleMinePath;
import com.example.baselibs.utils.ActivityUtils;
import com.example.baselibs.widget.FilletImageView;
import com.example.modulemine.R;
import com.example.modulemine.R2;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

@Route(path = ModuleMinePath.PATH_QR_CODE)
public class QRcodeActivity extends BaseToolBarActivity {
    @BindView(R2.id.iv_qr_code)
    FilletImageView iv_qr_code;
    private String apkURL;
    private int width;

    @Override
    public String setTitle() {
        return "应用二维码";
    }

    @Override
    public int getLayoutRes() {
        return R.layout.activity_qrcode;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        width=ActivityUtils.getScreenWidth(this)-200;
        getApkURL();
    }

    private Bitmap generateQRBitmap(String content,final int width,final int height){
        //创建对象
        QRCodeWriter qrCodeWriter=new QRCodeWriter();
        //用于保存二维码内容绘制的编码格式
        Map<EncodeHintType,String> hints=new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
        try {
            //设置绘制二维码的参数
            BitMatrix encode=qrCodeWriter.encode(content, BarcodeFormat.QR_CODE,width,height,hints);
            int[] pixels=new int[width*height];//存储矩形中bit的值
            for (int i=0;i<height;i++){
                for (int j=0;j<width;j++){
                    if (encode.get(j,i)){//获取请求的bit，如果为1，返回true，填充黑色,在矩形中，给定bit的值
                        pixels[i*width+j]=0x00000000;
                    }else {
                        pixels[i*width+j]=0xffffffff;
                    }
                }
            }
            return addLogo(Bitmap.createBitmap(pixels,0,width,width,height,Bitmap.Config.RGB_565),
                    BitmapFactory.decodeResource(getResources(),R.drawable.ic_qr_logo));
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 在二维码中间添加logo
     * @param qrBitmap
     * @param logoBitmap
     * @return
     */
    private Bitmap addLogo(Bitmap qrBitmap, Bitmap logoBitmap) {
        int qrBitmapWidth = qrBitmap.getWidth();
        int qrBitmapHeight = qrBitmap.getHeight();
        int logoBitmapWidth = logoBitmap.getWidth();
        int logoBitmapHeight = logoBitmap.getHeight();
        Bitmap blankBitmap = Bitmap.createBitmap(qrBitmapWidth, qrBitmapHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(blankBitmap);
        canvas.drawBitmap(qrBitmap, 0, 0, null);
        //canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.save();
        float scaleSize = 1.0f;
        while ((logoBitmapWidth / scaleSize) > (qrBitmapWidth / 4) || (logoBitmapHeight / scaleSize) > (qrBitmapHeight / 4)) {
            scaleSize *= 2;
        }
        float sx = 1.0f / scaleSize;
        canvas.scale(sx, sx, qrBitmapWidth / 2, qrBitmapHeight / 2);
        canvas.drawBitmap(logoBitmap, (qrBitmapWidth - logoBitmapWidth) / 2, (qrBitmapHeight - logoBitmapHeight) / 2, null);
        canvas.restore();
        return blankBitmap;
    }

    /**
     * 获取下载apk的链接
     */
    private void getApkURL(){

        Map<String, String> map = new HashMap<>();
        map.put("W", "SOFT_ID=1 AND ISTEST=0");
        map.put("O[UPDATE_TIME]", "DESC");
        map.put("L[0]", "1");
        RetrofitManager.getInstance().getUserApiService(UserApi.class).install(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result<UpdatedInfo>>() {
                    @Override
                    public void accept(Result<UpdatedInfo> updatedInfoResult) throws Exception {
                        if (updatedInfoResult.isStatus()){
                            apkURL=updatedInfoResult.getData().get(0).getDownload();
                            iv_qr_code.setImageBitmap(generateQRBitmap(apkURL,width,width));
                        }else {
                            ActivityUtils.showToast(getApplicationContext(),updatedInfoResult.getError());
                            Log.i("bbq","获取下载链接失败");
                            iv_qr_code.setImageBitmap(generateQRBitmap("apk下载链接",width,width));
                        }
                    }
                });
    }
}
